#include "database_worker.h"

#include "database_sql_op.h"
#include "pc_queue.h"

namespace afcore {
namespace database {

CDatabaseWorker::CDatabaseWorker(CPcQueue<CSqlOperation*>* new_queue, CMysqlConnection* conn)
  : queue_(new_queue)
  , conn_(conn) {
  worker_thread_ = std::thread(&CDatabaseWorker::WorkerThread, this);
}

CDatabaseWorker::~CDatabaseWorker() {
  cancel_action_token_ = true;
  queue_->Cancel();
  worker_thread_.join();
}

void CDatabaseWorker::WorkerThread() {
  if (!queue_) {
    return;
  }

  for (;;) {
    CSqlOperation* operation = nullptr;

    queue_->DequeueWait(operation);

    if (cancel_action_token_ || !operation) {
      return;
    }

    operation->SetConnection(conn_);
    operation->Call();

    delete operation;
  }
}

} // !namespace database
} // !namespace afcore